/*
 * Copyright 2020-2030 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
*/
package com.woodws.fresh.im.service.impl

import com.woodws.fresh.common.core.domain.R
import com.woodws.fresh.common.core.extra.copyProperties
import com.woodws.fresh.common.data.beetl.service.impl.BaseServiceImpl
import com.woodws.fresh.im.dao.ImSessionDao
import com.woodws.fresh.im.api.dto.ImSessionDto
import com.woodws.fresh.im.entity.ImSession
import com.woodws.fresh.im.api.service.ImSessionService
import org.apache.dubbo.config.annotation.DubboService
import org.springframework.data.redis.core.RedisTemplate
import org.springframework.stereotype.Service

/**
 * 消息服务登录会话表业务实现
 * @author maoxiaodong
*/
@DubboService
@Service
class ImSessionServiceImpl(val redisTemplate: RedisTemplate<String, Any>): ImSessionService, BaseServiceImpl<ImSessionDto, ImSession, ImSessionDao>(){

    override fun save(dto: ImSessionDto): R<ImSessionDto> {
        val entity = dtoToEntity(dto)
        dao.save(entity)
        redisTemplate.opsForValue()["imSession:${entity.userId}"] = dto
        return R.success(entityToDto(entity))
    }

    /**
     * 根据用户ID查询会话信息
     * @param userId 用户ID
     */
    override fun findByUserId(userId: Long): R<ImSessionDto>{
        var dto = redisTemplate.opsForValue()["imSession:${userId}"] as ImSessionDto
        if (dto == null){
            dto = dao.findByUserId(userId)?.copyProperties(ImSessionDto::class)
        }
        return R.success(dto)
    }

    /**
     * 根据用户ID查询会话信息
     * @param userId 用户ID
     * @return 返回删除数量
     */
    override fun deleteByUserId(userId: Long): R<Int>{
        redisTemplate.delete("imSession:${userId}")
        return R.success(dao.deleteByUserId(userId))
    }
}